<template>
  <el-dialog v-model="visible" width="900px" :title="!dataForm.id ? $t('add') : $t('update')"
    :close-on-click-modal="false" :close-on-press-escape="false">
    <el-form :model="dataForm" v-loading="loading" :rules="rules" ref="dataFormRef" @keyup.enter="dataFormSubmitHandle()"
      label-width="120px">

      <el-form-item label="标题" prop="title" class="full">
        <el-input v-model="dataForm.title" placeholder="用户名"></el-input>
      </el-form-item>
      <!-- <el-form-item label="年级" prop="gradeId" class="full">
        <el-select v-model="dataForm.gradeId" placeholder="选择年级">
          <el-option v-for="item in gradeList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="分类" prop="course" class="full">
        <el-select v-model="dataForm.subjectId" placeholder="选择分类">
          <el-option v-for="item in courseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="类型" prop="type" class="full">
        <el-select v-model="dataForm.type" placeholder="选择类型">
          <el-option v-for="item in eduTypeList" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="是否推荐" prop="isRecommend">
        <el-switch v-model="dataForm.isRecommend" inline-prompt :active-value="1" :inactive-value="0" active-text="是"
          inactive-text="否" />
      </el-form-item>
      <el-form-item label="是否热门" prop="isHot">
        <el-switch v-model="dataForm.isHot" inline-prompt :active-value="1" :inactive-value="0" active-text="是"
          inactive-text="否" />
      </el-form-item>

      <el-form-item label="备注" prop="content" class="full">
        <el-input type="textarea" :autosize="{ minRows: 3, maxRows: 6 }" v-model="dataForm.content"
          :placeholder="$t('task.notes')"></el-input>
      </el-form-item>
      <el-form-item prop="fileList" label="附件">
        <a :href="pdfUrl.filePath" style="marginTop: 20px">{{ uploadFileName }}</a>
        <el-upload class="avatar-uploader" :action="url + `/sys/oss/upload?token=${getToken()}`" :multiple="false"
          :show-file-list="false" :on-error="handleUploadError" :on-success="handleAvatarSuccess" :before-upload="beforeUploadHandle">
          <el-icon class="avatar-uploader-icon" v-if="!pdfLoading">
            <Plus />
          </el-icon>

          <el-icon class="avatar-uploader-icon" v-if="pdfLoading">
            <!-- <span style="fontSize: 14px">替换</span> -->
            <img :src="loadingGif" class="loadingImg"/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t("confirm") }}</el-button>
    </template>

  </el-dialog>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import baseService from "@/service/baseService";
import { useI18n } from "vue-i18n";
import { ElLoading, ElMessage } from "element-plus";
import { findObjectByPid, treeDataTranslate, validateMobile } from "@/utils/utils";
import { getToken } from "@/utils/cache";
import loadingGif from "@/assets/images/load.gif";
import { EduTypeList } from '@/constants/subject'

const url = import.meta.env.VITE_APP_API;
const { t } = useI18n();
const emit = defineEmits(["refreshDataList"]);
const loading = ref(false)
const visible = ref(false);
const dataFormRef = ref();
const pdfUrl = ref<any>({
  fileName: '',
  filePath: '',
});
const rules = ref({
  title: [{ required: true, message: t("validate.required"), trigger: ["blur", "change"] }],
});
const uploadFileName = ref<any>('');
let dataForm = reactive({
  title: "",
  content: "",
  subjectId: "",
  gradeId: "",
  gradeName: "",
  subjectName: "",
  type: "",
  fileUrl: "",
  isHot: false,
  isRecommend: false
});
const courseList = ref();
const gradeList = ref();
const multiFileList = ref([]);
// const pdfLoading = ref();
const eduTypeList = ref(EduTypeList);
const loadSuccess = ref(false);
const pdfLoading = ref(false);

onMounted(() => {
  handleSubjectList();
  handleGradeList();
});

const beforeUploadHandle = (file: any) => {

  const fileName = file.name;
  const fileType = fileName.substring(fileName.lastIndexOf('.'));
  if(fileType !== '.pdf' && fileType !== '.mp4' && fileType !== '.mp3'){
    ElMessage.error({
      message: '请上传pdf,mp4,mp3格式的文件',
      duration: 500,
    });
      return false;
  }
  uploadFileName.value = "";
  pdfLoading.value = true;
};

const handleSubjectList = async () => {
  try {
    const res = await baseService.get('/edu/subject/list')
    if (res.code == 0) {
      courseList.value = res.data;
    }
  } catch (error) {
    console.log('jj-error', error);
  }
}

const handleGradeList = async () => {
  try {
    const res = await baseService.get('/edu/grade/list')
    if (res.code == 0) {
      gradeList.value = res.data;
    }
  } catch (error) {
    console.log('jj-error', error);

  }
}

const init = (row?: any) => {
  console.log('jj-row', row);
  if (row) {
    dataForm = row
    pdfUrl.value = {
      filePath: row.fileUrl,
      fileName: row.title
    }
  }

  visible.value = true;
};

const handleAvatarSuccess = (data: any, uploadFile: any) => {
  if (data.code == 0) {
    const { fileName, filePath } = data?.data;
    dataForm.fileUrl = filePath;
    uploadFileName.value = fileName;
    pdfUrl.value = data?.data;
    ElMessage.success({
      message: t("prompt.success"),
      duration: 500,
    });
  } 
  loadSuccess.value = true;
  pdfLoading.value = false;
};

const handleUploadError = () => {
  ElMessage.success({
    message: "上传失败！",
    duration: 500,
  });
}


// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate(async (valid: boolean) => {
    if (!valid) {
      return false;
    }
    const {
      title,
      content,
      subjectId,
      gradeId,
      type,
      fileUrl,
      isHot,
      isRecommend
    } = dataForm
    console.log('jj-subjectId', subjectId);
    console.log('jj-courseList.value', courseList.value);

    const subjectName = courseList.value?.find((item: any) => item.id == dataForm?.subjectId)?.name;
    const gradeName = gradeList.value?.find((item: any) => item.id == dataForm?.gradeId)?.name;

    const parmas = {
      title,
      content,
      subjectId,
      gradeId,
      type,
      fileUrl,
      isHot,
      isRecommend,
      subjectName,
      gradeName
    }
    console.log('jj-dataForm', [parmas]);
    (!dataForm?.id ? baseService.post : baseService.put)('/edu/subject/file', dataForm?.id ? {
      ...parmas,
      id: dataForm.id,
    } : [parmas]).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });

    // (!dataForm.id ? baseService.post : baseService.put)("/assess/user", {
    //   ...dataForm,
    //   freeTime: dataForm?.freeTime?.join(',')
    // }).then((res) => {
    //   ElMessage.success({
    //     message: t("prompt.success"),
    //     duration: 500,
    //     onClose: () => {
    //       visible.value = false;
    //       emit("refreshDataList");
    //     }
    //   });
    // });
  });
};

defineExpose({
  init
});
</script>
<style lang="less" scoped>
:deep(.el-dialog__body) {
  padding: 0 20px 20px 20px !important;
  max-height: calc(90vh - 116px);
}

:deep(.el-form-item) {
  width: calc(50% - 16px);

  &.full {
    width: 100%;

    &.address {
      display: flex;
    }
  }

  &.area-form-item {
    width: calc(33% - 16px);
  }
}

:deep(.el-form-item__content) {
  flex-direction: column;
  align-content: flex-start !important;
  justify-content: flex-start;
}

:deep(.el-form-item--default .el-form-item__content) {
  align-content: flex-start !important;
}

.additionFile {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
}

.loadingImg {
  width: 60px;
  height: 60px;
}
</style>
